import 'package:flutter/material.dart';
import '../../widgets/news_card.dart';
import '../../models/news_model.dart';
import '../../routes/Router.dart';
import '../../services/umeng_analytics.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({super.key});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final TextEditingController _searchController = TextEditingController();
  List<NewsModel> _searchResults = [];
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    UmengAnalytics.onPageStart('SearchPage');
  }

  @override
  void dispose() {
    _searchController.dispose();
    UmengAnalytics.onPageEnd('SearchPage');
    super.dispose();
  }

  void _performSearch(String query) {
    if (query.isEmpty) {
      setState(() {
        _searchResults = [];
        _isSearching = false;
      });
      return;
    }

    setState(() {
      _isSearching = true;
    });

    // 模拟搜索结果
    Future.delayed(const Duration(milliseconds: 500), () {
      if (!mounted) return;

      final results = List.generate(
        5,
        (index) => NewsModel(
          id: 'search_${query}_$index',
          title: '搜索结果: $query - 新闻标题 $index',
          content: '这是与"$query"相关的新闻内容，包含相关内容和详细信息。',
          imageUrl: index % 2 == 0
              ? ''
              : 'https://picsum.photos/400/300?random=${200 + index}',
          category: ['科技', '体育', '娱乐', '财经'][index % 4],
          publishTime: DateTime.now().subtract(Duration(days: index)),
          author: ['记者A', '记者B', '记者C'][index % 3],
        ),
      );

      setState(() {
        _searchResults = results;
        _isSearching = false;
      });

      UmengAnalytics.onEvent(
        'search',
        properties: {'query': query, 'result_count': results.length},
      );
    });
  }

  void _onNewsTap(NewsModel news) {
    Navigator.pushNamed(
      context,
      AppRoutes.newsDetail,
      arguments: {'id': news.id, 'title': news.title},
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: TextField(
            controller: _searchController,
            decoration: const InputDecoration(
              hintText: '请输入搜索关键词',
              prefixIcon: Icon(Icons.search),
              border: OutlineInputBorder(),
            ),
            onSubmitted: _performSearch,
          ),
        ),
        if (_isSearching)
          const Padding(
            padding: EdgeInsets.all(16),
            child: Center(child: CircularProgressIndicator()),
          ),
        Expanded(
          child: ListView.builder(
            itemCount: _searchResults.length,
            itemBuilder: (context, index) {
              return NewsCard(
                news: _searchResults[index],
                onTap: () => _onNewsTap(_searchResults[index]),
              );
            },
          ),
        ),
      ],
    );
  }
}
